package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.model.MiniLoginUser;
import com.ruoyi.system.domain.MyHistory;
import com.ruoyi.system.domain.MyTheme;
import com.ruoyi.system.domain.vo.ChatVo;
import com.ruoyi.system.mapper.MyHistoryMapper;
import com.ruoyi.system.mapper.MyThemeMapper;
import com.ruoyi.system.service.IMyHistoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class IMyHistoryServiceImpl extends ServiceImpl<MyHistoryMapper, MyHistory> implements IMyHistoryService {

    @Autowired
    private MyHistoryMapper myHistoryMapper;
    @Autowired
    private MyThemeMapper myThemeMapper;

    /**
     * 查询聊天列表（首页）
     */
    @Override
    public List<ChatVo> selectMyHistoryList(String keyword, MiniLoginUser currentUser) {
        List<ChatVo> chatVoList = new ArrayList<>();
        if (currentUser.getType() == 0) {
            // 用户
            // 查询聊过的主题
            List<ChatVo> chatVos = myHistoryMapper.tidList(currentUser.getId());
            for (ChatVo chatVo : chatVos) {
                // 查询未读数量
                LambdaQueryWrapper<MyHistory> countQueryWrapper = new LambdaQueryWrapper<>();
                countQueryWrapper.eq(MyHistory::getTid, chatVo.getTid())
                        .eq(MyHistory::getUid, currentUser.getId())
                        .isNull(MyHistory::getReadStatus)
                        .eq(MyHistory::getChatType, 1);
                int unread = this.count(countQueryWrapper);
                chatVo.setUnread(unread);

                // 查询最后一条记录
                LambdaQueryWrapper<MyHistory> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(MyHistory::getTid, chatVo.getTid())
                        .eq(MyHistory::getUid, currentUser.getId())
                        .orderByDesc(MyHistory::getCreateTime)
                        .last("limit 1");
                MyHistory myHistory = this.getOne(queryWrapper);
                if (myHistory != null) {
                    chatVo.setId(myHistory.getId());
                    chatVo.setUid(myHistory.getUid());
                    chatVo.setContent(myHistory.getContent());
                    chatVo.setContentType(myHistory.getContentType());
                    chatVo.setChatType(myHistory.getChatType());
                    chatVo.setCreateTime(myHistory.getCreateTime());
                }
            }
            chatVoList.addAll(chatVos);
        } else {
            // 回复人-管理多个主题
            LambdaQueryWrapper<MyTheme> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(MyTheme::getRid, currentUser.getId())
                    .eq(MyTheme::getStatus, 1);
            List<MyTheme> myThemes = myThemeMapper.selectList(queryWrapper1);

            for (MyTheme myTheme : myThemes) {
                // 查询聊过的用户
                List<ChatVo> chatVos = myHistoryMapper.uidList(myTheme.getId(), keyword);
                for (ChatVo chatVo : chatVos) {
                    // 查询未读数量
                    LambdaQueryWrapper<MyHistory> countQueryWrapper = new LambdaQueryWrapper<>();
                    countQueryWrapper.eq(MyHistory::getTid, myTheme.getId())
                            .eq(MyHistory::getUid, chatVo.getUid())
                            .isNull(MyHistory::getReadStatus)
                            .eq(MyHistory::getChatType, 0);
                    int unread = this.count(countQueryWrapper);
                    chatVo.setUnread(unread);

                    // 查询最后一条记录
                    LambdaQueryWrapper<MyHistory> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(MyHistory::getTid, myTheme.getId())
                            .eq(MyHistory::getUid, chatVo.getUid())
                            .orderByDesc(MyHistory::getCreateTime)
                            .last("limit 1");
                    MyHistory myHistory = this.getOne(queryWrapper);
                    if (myHistory != null) {
                        chatVo.setId(myHistory.getId());
                        chatVo.setTid(myHistory.getTid());
                        chatVo.setContent(myHistory.getContent());
                        chatVo.setContentType(myHistory.getContentType());
                        chatVo.setChatType(myHistory.getChatType());
                        chatVo.setCreateTime(myHistory.getCreateTime());
                    }
                }
                chatVoList.addAll(chatVos);
            }
        }

        return setDate(chatVoList);
    }

    private List<ChatVo> setDate(List<ChatVo> chatVoList) {
        String oldDate = "";
        for (ChatVo chatVo : chatVoList) {
            String date = "";
            if (chatVo.getCreateTime().getYear() == LocalDateTime.now().getYear()) {
                // 今年
                if (chatVo.getCreateTime().getMonthValue() == LocalDateTime.now().getMonthValue()) {
                    if (chatVo.getCreateTime().getDayOfMonth() == LocalDateTime.now().getDayOfMonth()) {
                        date = chatVo.getCreateTime().getHour() + ":" + chatVo.getCreateTime().getMinute();
                    } else if (chatVo.getCreateTime().getDayOfMonth() == LocalDateTime.now().getDayOfMonth() - 1) {
                        date = "昨天 " + chatVo.getCreateTime().getHour() + ":" + chatVo.getCreateTime().getMinute();
                    } else {
                        date = chatVo.getCreateTime().getMonthValue() + "月" + chatVo.getCreateTime().getDayOfMonth() + "日";
                    }
                } else {
                    date = chatVo.getCreateTime().getMonthValue() + "月" + chatVo.getCreateTime().getDayOfMonth() + "日";
                }
            } else {
                date = chatVo.getCreateTime().getYear() + "/" + chatVo.getCreateTime().getMonthValue() + "/" + chatVo.getCreateTime().getDayOfMonth();
            }

            if (!oldDate.equals(date)) {
                oldDate = date;
                chatVo.setDate(date);
            }
        }
        return chatVoList;
    }

    /**
     * 查询历史记录（聊天页面）
     */
    @Override
    public List<MyHistory> selectMyHistory(MyHistory myHistory) {
        // 更新未读
        updateUnread(myHistory);

        // 查询记录
        LambdaQueryWrapper<MyHistory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MyHistory::getTid, myHistory.getTid())
                .eq(MyHistory::getUid, myHistory.getUid())
                .orderByAsc(MyHistory::getCreateTime);
        List<MyHistory> myHistoryList = this.list(queryWrapper);

        return setDateAndTime(myHistoryList);
    }

    private void updateUnread(MyHistory myHistory) {
        LambdaQueryWrapper<MyHistory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MyHistory::getTid, myHistory.getTid())
                .eq(MyHistory::getUid, myHistory.getUid())
                .isNull(MyHistory::getReadStatus)
                .last("limit 1");
        MyHistory last = this.getOne(queryWrapper);
        if (last == null)
            return;

        if (myHistory.getChatType() == last.getChatType()) {
            return;
        }

        LambdaUpdateWrapper<MyHistory> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(MyHistory::getTid, myHistory.getTid())
                .eq(MyHistory::getUid, myHistory.getUid())
                .set(MyHistory::getReadStatus, 1);
        this.update(updateWrapper);
    }

    private List<MyHistory> setDateAndTime(List<MyHistory> myHistoryList) {
        String oldDate = "";
        for (MyHistory history : myHistoryList) {
            String date = "";
            if (history.getCreateTime().getYear() == LocalDateTime.now().getYear()) {
                // 今年
                if (history.getCreateTime().getMonthValue() == LocalDateTime.now().getMonthValue()) {
                    if (history.getCreateTime().getDayOfMonth() == LocalDateTime.now().getDayOfMonth()) {
                        date = "今天";
                    } else if (history.getCreateTime().getDayOfMonth() == LocalDateTime.now().getDayOfMonth() - 1) {
                        date = "昨天";
                    } else if (history.getCreateTime().getDayOfMonth() == LocalDateTime.now().getDayOfMonth() - 2) {
                        date = "前天";
                    } else {
                        date = history.getCreateTime().getMonthValue() + "月" + history.getCreateTime().getDayOfMonth() + "日";
                    }
                } else {
                    date = history.getCreateTime().getMonthValue() + "月" + history.getCreateTime().getDayOfMonth() + "日";
                }
            } else {
                date = history.getCreateTime().getYear() + "年" + history.getCreateTime().getMonthValue() + "月" + history.getCreateTime().getDayOfMonth() + "日";
            }

            if (!oldDate.equals(date)) {
                oldDate = date;
                history.setDate(date);
            }
            history.setTime(history.getCreateTime().getHour() + ":" + history.getCreateTime().getMinute());
        }
        return myHistoryList;
    }

}
